import re
from rest_framework import serializers

from users.models import Address
from .models import Area


class AreaSerializer(serializers.ModelSerializer):
    '''
    行政区划信息序列化器
    '''
    class Meta:
        model = Area
        fields = '__all__'


class AddressesSerializer(serializers.ModelSerializer):

    # 显示指明字段
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    class Meta:
        model = Address
        exclude = ('user',)

    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def create(self, validated_data):

        user = self.context['request'].user
        # 需要在验证后的数据中添加user
        validated_data['user'] = user
        address = super().create(validated_data)

        return address